//
//  Mu_BaseTabBarController.m
//  NewMarryU
//
//  Created by Cedar on 2018/7/10.
//  Copyright © 2018年 Cedar. All rights reserved.
//

#import "M1TabBarController.h"
#import "M1HomeViewController.h"
#import "M1ColumnViewController.h"
#import "M1PersonalViewController.h"
#import <UserNotifications/UserNotifications.h>
#import "AppDelegate.h"
#import "M1DiagnosisViewController.h"
#import "M1ShopViewController.h"
static const CGFloat kDefaultPlaySoundInterval = 3.0;
static NSString *kMessageType = @"MessageType";
static NSString *kConversationChatter = @"ConversationChatter";
@interface M1TabBarController ()<UITabBarControllerDelegate>
@property (nonatomic ,strong) NSMutableArray *m1_viewModels;
@property (strong, nonatomic) NSDate *m1_lastPlaySoundDate;
@end

@implementation M1TabBarController
+ (instancetype)instance{
    AppDelegate *delegete = (AppDelegate *)[UIApplication sharedApplication].delegate;
    UIViewController *vc = delegete.window.rootViewController;
    if ([vc isKindOfClass:[M1TabBarController class]]) {
        return (M1TabBarController *)vc;
    }else{
        return [M1TabBarController new];
    }
}
- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
-(NSMutableArray *)m1_viewModels{
    if (!_m1_viewModels) {
        _m1_viewModels = [NSMutableArray arrayWithCapacity:0];
        
        NSArray *views = @[NSStringFromClass([M1HomeViewController class]),
                           NSStringFromClass([M1ColumnViewController class]),
                           NSStringFromClass([M1MessageListVC class]),
                           NSStringFromClass([M1PersonalViewController class])];
        NSArray *titles = @[@"寻Ta",@"专区",@"消息",@"我的"];
        NSArray *images = @[@"home_n",@"zone_n",@"msg_n",@"person_n"];
        NSArray *selectedImages = @[@"home_s",@"zone_s",@"msg_s",@"person_s"];
        
        
        if ([M1SaveTool m1_appConfig].is_vest_value || [M1User user].status.is_app_vest) {
            views = @[NSStringFromClass([M1HomeViewController class]),
                      NSStringFromClass([M1DiagnosisViewController class]),
                      NSStringFromClass([M1ShopViewController class]),
                      NSStringFromClass([M1MessageListVC class]),
                      NSStringFromClass([M1PersonalViewController class])];
            titles = @[@"寻Ta",@"诊断",@"商城",@"消息",@"我的"];
            images = @[@"home_n",@"diagnosis_n",@"shop_n",@"msg_n",@"person_n"];
            selectedImages = @[@"home_s",@"diagnosis_s",@"shop_s",@"msg_s",@"person_s"];
        }
        
        for (int i = 0; i<views.count; i++) {
            M1TabBarModel *model = [M1TabBarModel new];
            model.m1_className = views[i];
            model.m1_image = images[i];
            model.m1_selectedImage = selectedImages[i];
            model.m1_title = titles[i];
            
            [_m1_viewModels addObject:model];
        }
    }
    
    return _m1_viewModels;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    NSMutableArray *m1_tabars = [NSMutableArray arrayWithCapacity:0];
    WEAKSELF;
    [self.m1_viewModels enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        M1TabBarModel *model = (M1TabBarModel *)obj;
        Class class = NSClassFromString(model.m1_className);
        
        M1BaseViewController *vc = [[class alloc]init];
        if ([NSStringFromClass(class) isEqualToString:NSStringFromClass([M1MessageListVC class])]) {
            weakSelf.m1_messageListVC =(M1MessageListVC *)vc;
        }
        M1NavigationController *m1_nav = [[M1NavigationController alloc]initWithRootViewController:vc];
        m1_nav.tabBarItem = [[UITabBarItem alloc]initWithTitle:model.m1_title
                                                         image:[[UIImage imageNamed:model.m1_image] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]
                                                 selectedImage:[[UIImage imageNamed:model.m1_selectedImage] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]];
        [m1_nav.tabBarItem setTitlePositionAdjustment:UIOffsetMake(0, -2)];
        m1_nav.tabBarItem.tag = idx;
        [m1_tabars addObject:m1_nav];
    }];

    self.tabBar.translucent = NO;    // 半透明
    self.tabBar.alpha = 1;
    self.tabBar.backgroundColor = [UIColor whiteColor];
    self.viewControllers = m1_tabars;
    self.delegate= self;
    self.tabBar.contentMode = UIViewContentModeScaleAspectFill;
    [self.tabBar setTintColor:[UIColor m1_colorHex:0x343434]];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(m1_updateUnReadMessage) name:@"setupUnreadMessageCount" object:nil];
    [self m1_updateUnReadMessage];
}
-(BOOL)tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController{
    if (![M1User user]) {
        NSInteger index = 1;
        
        if ([M1SaveTool m1_appConfig].is_vest_value|| [M1User user].status.is_app_vest){
            index = 2;
        }
        if(viewController.tabBarItem.tag >index){
            WEAKSELF;
            [M1Alert m1_alertWithTitle:nil message:m1_loginText buttonTitles:@[@"取消",@"登录"] action:^(NSInteger index) {
                if (index == 1) {
                    M1LoginVC *m1_loginVC = [M1LoginVC new];
                    m1_loginVC.m1_changeBackImage = YES;
                    m1_loginVC.m1_changeNavTitleColor = YES;
                    m1_loginVC.hidesBottomBarWhenPushed = YES;
                    [weakSelf.selectedViewController pushViewController:m1_loginVC animated:YES];
                }
            }];
            
            
            return NO;
        }
    }
    return YES;
}
-(void)m1_updateUnReadMessage{
    NSArray *conversations = [[EMClient sharedClient].chatManager getAllConversations];
    NSInteger unreadCount = 0;
    for (EMConversation *conversation in conversations) {
        unreadCount += conversation.unreadMessagesCount;
    }
    M1NavigationController *nav = self.viewControllers[2];
    if ([M1SaveTool m1_appConfig].is_vest_value || [M1User user].status.is_app_vest){
        nav = self.viewControllers[3];
    }
    nav.tabBarItem.badgeValue = unreadCount ? (unreadCount >99?@"N+":@(unreadCount).stringValue) : nil;
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:unreadCount];
}

- (void)m1_playSound{
    NSTimeInterval timeInterval = [[NSDate date]
                                   timeIntervalSinceDate:self.m1_lastPlaySoundDate];
    if (timeInterval < kDefaultPlaySoundInterval) {
        NSLog(@"skip ringing & vibration %@, %@", [NSDate date], self.m1_lastPlaySoundDate);
        return;
    }
    self.m1_lastPlaySoundDate = [NSDate date];
    [[EMCDDeviceManager sharedInstance] playNewMessageSound];
    [[EMCDDeviceManager sharedInstance] playVibration];
}
- (void)m1_showMessageNotification:(EMMessage *)message{
    NSString *m1_alertBody = nil;
    m1_alertBody = NSLocalizedString(@"receiveMessage", @"you have a new message");
    NSTimeInterval timeInterval = [[NSDate date] timeIntervalSinceDate:self.m1_lastPlaySoundDate];
    BOOL playSound = NO;
    if (!self.m1_lastPlaySoundDate || timeInterval >= kDefaultPlaySoundInterval) {
        self.m1_lastPlaySoundDate = [NSDate date];
        playSound = YES;
    }
    NSMutableDictionary *userInfo = [NSMutableDictionary dictionary];
    [userInfo setObject:[NSNumber numberWithInt:message.chatType] forKey:kMessageType];
    [userInfo setObject:message.conversationId forKey:kConversationChatter];
    if (NSClassFromString(@"UNUserNotificationCenter")) {
        UNTimeIntervalNotificationTrigger *trigger = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:0.01 repeats:NO];
        UNMutableNotificationContent *m1_content = [[UNMutableNotificationContent alloc] init];
        if (playSound) {
            m1_content.sound = [UNNotificationSound defaultSound];
        }
        m1_content.body =m1_alertBody;
        m1_content.userInfo = userInfo;
        UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:message.messageId content:m1_content trigger:trigger];
        [[UNUserNotificationCenter currentNotificationCenter] addNotificationRequest:request withCompletionHandler:nil];
    }
    else {
        UILocalNotification *m1_notif = [[UILocalNotification alloc] init];
        m1_notif.fireDate = [NSDate date];
        m1_notif.alertBody = m1_alertBody;
        m1_notif.alertAction = NSLocalizedString(@"open", @"Open");
        m1_notif.timeZone = [NSTimeZone defaultTimeZone];
        if (playSound) {
            m1_notif.soundName = UILocalNotificationDefaultSoundName;
        }
        m1_notif.userInfo = userInfo;
        [[UIApplication sharedApplication] scheduleLocalNotification:m1_notif];
    }
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

@implementation M1TabBarModel


@end

